namespace LicenseApp.Client;

/// <summary>
/// 授权状态回调委托
/// </summary>
public delegate void LicenseStatusCallback(LicenseStatusInfo statusInfo);

/// <summary>
/// 授权管理器 - 客户端主要API入口
/// </summary>
public static class LicenseManager
{
    private static LicenseMonitor? _monitor;
    private static bool _isWorking = false;
    private static bool _pendingExpiredNotification = false;
    private static LicenseStatusCallback? _statusCallback;
    private static ILicenseNotifier? _notifier;

    /// <summary>
    /// 初始化授权系统
    /// </summary>
    /// <param name="publicKeyXml">RSA公钥XML字符串</param>
    /// <returns>是否初始化成功</returns>
    public static bool Initialize(string publicKeyXml)
    {
        return LicenseValidator.SetPublicKey(publicKeyXml);
    }

    /// <summary>
    /// 注册授权码
    /// </summary>
    /// <param name="licenseCode">授权码</param>
    /// <returns>是否注册成功</returns>
    public static bool RegisterLicense(string licenseCode)
    {
        var result = LicenseValidator.RegisterLicense(licenseCode);

        // 如果注册成功且监控器正在运行，立即检查状态
        if (result && _monitor != null)
        {
            _monitor.CheckNow();
        }

        return result;
    }

    /// <summary>
    /// 后台注册授权码（用于客户端应用的预先隐藏授权码注册）
    /// </summary>
    /// <param name="licenseCode">授权码</param>
    /// <param name="allowDuplicateRegistration">是否允许重复注册相同授权码</param>
    /// <returns>注册结果</returns>
    public static LicenseRegistrationResult RegisterLicenseBackground(string licenseCode, bool allowDuplicateRegistration = false)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(licenseCode))
            {
                return new LicenseRegistrationResult
                {
                    Success = false,
                    Message = "授权码不能为空",
                    ErrorType = LicenseRegistrationErrorType.InvalidInput
                };
            }

            // 检查注册风险（传入重复注册控制参数）
            var riskCheck = LicenseValidator.GetRegistrationRisk(licenseCode, allowDuplicateRegistration);

            if (!riskCheck.CanRegister)
            {
                // 不能注册的情况（通常是相同授权码且不允许重复注册）
                return new LicenseRegistrationResult
                {
                    Success = false,
                    Message = riskCheck.Message,
                    ErrorType = LicenseRegistrationErrorType.DuplicateRegistration,
                    RiskLevel = riskCheck.RiskLevel
                };
            }

            // 执行注册
            bool success;
            if (riskCheck.RequiresConfirmation)
            {
                // 需要确认的情况（包括允许重复注册的相同授权码），使用带确认参数的注册方法
                success = LicenseValidator.RegisterLicense(licenseCode, true);
            }
            else
            {
                // 安全注册，直接执行
                success = LicenseValidator.RegisterLicense(licenseCode);
            }

            // 如果注册成功且监控器正在运行，立即检查状态
            if (success && _monitor != null)
            {
                _monitor.CheckNow();
            }

            return new LicenseRegistrationResult
            {
                Success = success,
                Message = success ? "授权码注册成功" : "授权码注册失败",
                ErrorType = success ? LicenseRegistrationErrorType.None : LicenseRegistrationErrorType.RegistrationFailed,
                RiskLevel = riskCheck.RiskLevel
            };
        }
        catch (Exception ex)
        {
            return new LicenseRegistrationResult
            {
                Success = false,
                Message = $"注册过程中发生错误: {ex.Message}",
                ErrorType = LicenseRegistrationErrorType.Exception
            };
        }
    }

    /// <summary>
    /// 检查授权是否有效
    /// </summary>
    /// <returns>是否有效</returns>
    public static bool IsLicenseValid()
    {
        return LicenseValidator.IsLicenseValid();
    }

    /// <summary>
    /// 获取授权信息
    /// </summary>
    /// <returns>授权信息</returns>
    public static LicenseInfo? GetLicenseInfo()
    {
        return LicenseValidator.GetLicenseInfo();
    }

    /// <summary>
    /// 开始监控授权状态
    /// </summary>
    /// <returns>授权监控器实例</returns>
    public static LicenseMonitor StartMonitoring()
    {
        StopMonitoring(); // 停止之前的监控

        _monitor = new LicenseMonitor();
        _monitor.Start();
        return _monitor;
    }

    /// <summary>
    /// 停止监控授权状态
    /// </summary>
    public static void StopMonitoring()
    {
        if (_monitor != null)
        {
            _monitor.Stop();
            _monitor.Dispose();
            _monitor = null;
        }
    }

    /// <summary>
    /// 清除授权信息
    /// </summary>
    /// <returns>是否清除成功</returns>
    public static bool ClearLicense()
    {
        var result = LicenseValidator.ClearLicense();
        
        // 如果清除成功且监控器正在运行，立即检查状态
        if (result && _monitor != null)
        {
            _monitor.CheckNow();
        }

        return result;
    }

    /// <summary>
    /// 获取当前监控器实例
    /// </summary>
    /// <returns>监控器实例，如果未启动则返回null</returns>
    public static LicenseMonitor? GetMonitor()
    {
        return _monitor;
    }

    /// <summary>
    /// 立即检查授权状态（如果监控器正在运行）
    /// </summary>
    public static void CheckNow()
    {
        _monitor?.CheckNow();
    }

    // === 新增的增强API ===

    /// <summary>
    /// 启动授权监控（带回调）
    /// </summary>
    /// <param name="callback">状态变化回调</param>
    /// <param name="checkInterval">检查间隔，默认10分钟</param>
    /// <returns>是否启动成功</returns>
    public static bool StartLicenseMonitoring(LicenseStatusCallback callback, TimeSpan? checkInterval = null)
    {
        try
        {
            _statusCallback = callback;

            StopMonitoring(); // 停止之前的监控

            _monitor = new LicenseMonitor();

            // 注册事件处理
            _monitor.LicenseStatusChanged += OnLicenseStatusChanged;
            _monitor.LicenseExpiring += OnLicenseExpiring;
            _monitor.LicenseExpired += OnLicenseExpired;

            _monitor.Start();

            // 立即执行一次检查
            CheckLicenseStatusInternal();

            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 启动授权监控（带通知器）
    /// </summary>
    /// <param name="callback">状态变化回调</param>
    /// <param name="notifier">通知器实现</param>
    /// <param name="checkInterval">检查间隔，默认10分钟</param>
    /// <returns>是否启动成功</returns>
    public static bool StartLicenseMonitoring(LicenseStatusCallback callback, ILicenseNotifier notifier, TimeSpan? checkInterval = null)
    {
        _notifier = notifier;
        return StartLicenseMonitoring(callback, checkInterval);
    }

    /// <summary>
    /// 设置通知器
    /// </summary>
    /// <param name="notifier">通知器实现</param>
    public static void SetNotifier(ILicenseNotifier notifier)
    {
        _notifier = notifier;
    }

    /// <summary>
    /// 显示非阻塞通知
    /// </summary>
    /// <param name="message">消息内容</param>
    /// <param name="status">授权状态</param>
    public static void ShowNotification(string message, LicenseStatus status = LicenseStatus.Valid)
    {
        try
        {
            // 如果没有设置通知器，使用默认的自定义窗口通知器
            if (_notifier == null)
            {
                _notifier = new CustomWindowNotifier();
            }

            _notifier.ShowNotification(message, status);
        }
        catch
        {
            // 如果通知失败，尝试控制台输出
            try
            {
                var consoleNotifier = new ConsoleNotifier();
                consoleNotifier.ShowNotification(message, status);
            }
            catch
            {
                // 忽略所有通知错误
            }
        }
    }

    /// <summary>
    /// 获取当前缓存的授权状态
    /// </summary>
    public static LicenseStatusInfo GetCurrentStatus()
    {
        return LicenseValidator.GetLicenseStatus();
    }

    /// <summary>
    /// 获取缓存的授权信息（立即返回，不重新验证）
    /// </summary>
    public static LicenseInfo? GetCachedLicenseInfo()
    {
        return LicenseValidator.GetLicenseInfo();
    }

    /// <summary>
    /// 强制刷新授权缓存
    /// </summary>
    public static bool RefreshLicenseCache()
    {
        try
        {
            // 清除缓存，强制重新读取
            var licenseInfo = LicenseValidator.GetLicenseInfo();
            return licenseInfo != null;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 检查是否可以继续工作（考虑宽限期）
    /// </summary>
    public static bool CanContinueWork()
    {
        var status = GetCurrentStatus();
        return status.Status != LicenseStatus.Expired;
    }

    /// <summary>
    /// 设置工序执行状态（防止在关键时刻中断）
    /// </summary>
    public static void SetWorkingState(bool isWorking)
    {
        _isWorking = isWorking;

        // 工序完成时，检查是否有待处理的过期通知
        if (!isWorking && _pendingExpiredNotification)
        {
            _pendingExpiredNotification = false;
            var status = GetCurrentStatus();
            _statusCallback?.Invoke(status);
        }
    }

    /// <summary>
    /// 快速检查授权状态（优先使用缓存）
    /// </summary>
    public static bool IsAuthorized()
    {
        return IsLicenseValid();
    }

    /// <summary>
    /// 快速获取剩余天数
    /// </summary>
    public static int GetRemainingDays()
    {
        var status = GetCurrentStatus();
        return status.RemainingDays;
    }

    /// <summary>
    /// 是否即将到期
    /// </summary>
    public static bool IsExpiringSoon()
    {
        var status = GetCurrentStatus();
        return status.Status == LicenseStatus.ExpiringSoon;
    }

    /// <summary>
    /// 🎯 获取详细的验证规则信息
    /// </summary>
    public static ValidationRuleDetails? GetValidationRuleDetails()
    {
        var status = GetCurrentStatus();
        return status.RuleDetails;
    }

    /// <summary>
    /// 🎯 获取完整的验证结果
    /// </summary>
    public static LicenseValidationResult? GetValidationResult()
    {
        var status = GetCurrentStatus();
        return status.ValidationResult;
    }

    /// <summary>
    /// 🎯 检查是否为时间回拨错误
    /// </summary>
    public static bool IsTimeRollbackError()
    {
        var details = GetValidationRuleDetails();
        return details?.HasTimeRollback == true;
    }

    /// <summary>
    /// 🎯 检查是否为时间停滞错误
    /// </summary>
    public static bool IsTimeStagnationError()
    {
        var details = GetValidationRuleDetails();
        return details?.HasTimeStagnation == true;
    }

    /// <summary>
    /// 🎯 获取停滞小时数
    /// </summary>
    public static double GetStagnantHours()
    {
        var details = GetValidationRuleDetails();
        return details?.StagnantHours ?? 0;
    }

    // === 内部事件处理 ===

    private static void OnLicenseStatusChanged(object? sender, LicenseStatusEventArgs e)
    {
        CheckLicenseStatusInternal();
    }

    private static void OnLicenseExpiring(object? sender, LicenseReminderEventArgs e)
    {
        CheckLicenseStatusInternal();
    }

    private static void OnLicenseExpired(object? sender, LicenseExpiredEventArgs e)
    {
        CheckLicenseStatusInternal();
    }

    private static void CheckLicenseStatusInternal()
    {
        try
        {
            var status = GetCurrentStatus();

            // 工序保护：如果正在执行关键工序且状态为过期，延迟通知
            if (_isWorking && status.Status == LicenseStatus.Expired)
            {
                _pendingExpiredNotification = true;
                return;
            }

            // 触发回调
            _statusCallback?.Invoke(status);
        }
        catch
        {
            // 忽略检查过程中的异常
        }
    }
}

/// <summary>
/// 授权注册结果
/// </summary>
public class LicenseRegistrationResult
{
    /// <summary>
    /// 是否注册成功
    /// </summary>
    public bool Success { get; set; }

    /// <summary>
    /// 结果消息
    /// </summary>
    public string Message { get; set; } = "";

    /// <summary>
    /// 错误类型
    /// </summary>
    public LicenseRegistrationErrorType ErrorType { get; set; } = LicenseRegistrationErrorType.None;

    /// <summary>
    /// 注册风险级别
    /// </summary>
    public RegistrationRiskLevel RiskLevel { get; set; } = RegistrationRiskLevel.Safe;
}

/// <summary>
/// 授权注册错误类型
/// </summary>
public enum LicenseRegistrationErrorType
{
    /// <summary>
    /// 无错误
    /// </summary>
    None,

    /// <summary>
    /// 输入无效
    /// </summary>
    InvalidInput,

    /// <summary>
    /// 重复注册
    /// </summary>
    DuplicateRegistration,

    /// <summary>
    /// 注册失败
    /// </summary>
    RegistrationFailed,

    /// <summary>
    /// 异常错误
    /// </summary>
    Exception
}
